package com.mybatis.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.mybatis.io.Resources;
import com.mybatis.pojo.Configuration;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Properties;

public class XMLConfigBuilder {
    private Configuration configuration;

    public XMLConfigBuilder() {
        this.configuration = new Configuration();
    }

    public Configuration parseConfig(InputStream in)
            throws DocumentException,
            PropertyVetoException {
        //解析配置文件获取数据源链接信息
        Document document = new SAXReader().read(in);
        Element root = document.getRootElement();
        List<Element> elements = root.selectNodes("//property");
        Properties properties = new Properties();
        for (Element element : elements) {
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            properties.setProperty(name,value);
        }
        ComboPooledDataSource pooledDataSource = new ComboPooledDataSource();
        pooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        pooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        pooledDataSource.setUser(properties.getProperty("username"));
        pooledDataSource.setPassword(properties.getProperty("password"));
        configuration.setDataSource(pooledDataSource);

        List<Element> mapperList = root.selectNodes("//mapper");
        for (Element element : mapperList) {
            String resource = element.attributeValue("resource");
            InputStream inputStream = Resources.getResourceAsStream(resource);
            XMLMapperBuilder mapperBuilder = new XMLMapperBuilder(configuration);
            mapperBuilder.parse(inputStream);
        }
        return configuration;
    }
}
